<template>
  <h1>App...</h1>
  <p>{{ count }}</p>
  <button @click="handleClick">按钮</button>
  <p>{{ user.phone }}</p>
  <p>{{ user.password }}</p>
  <button @click="setPassword">更新password</button>
  <p>{{ text }}</p>

  <Child :count="count" @setCount="handleClick"/>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, watch, computed, onBeforeUnmount, onMounted } from "vue";
import Child from "./Child.vue";

export default defineComponent({
  name: "App",
  setup() {
    // beforeCreate和created
    console.log("setup");

    // 生命周期
    onMounted(() => {
      console.log("mounted111");
    });

    onMounted(() => {
      console.log("mounted222");
    });

    onMounted(() => {
      console.log("mounted333");
    });

    onBeforeUnmount(() => {
      console.log("onBeforeUnmount");
    });

    // 定义响应式数据
    // 如果是表单项数据使用reactive
    // 非表单项用ref
    // const count = ref<number>(0);
    const count = ref(0);
    // const arr = ref<number[]>([]);
    // arr.value.push(11);

    // 定义methods
    const handleClick = () => {
      // 在setup函数中访问ref定义的响应式数据，必须xxx.value
      count.value++;
    };

    // 使用监视属性
    watch(
      count,
      (newVal, oldVal) => {
        console.log(newVal, oldVal);
      },
      {
        // immediate: true,
        // deep: true,
      }
    );

    // 计算属性
    // 只读的计算属性
    const text = computed(() => {
      return `${count.value}次`;
    });

    // 可读可写
    // computed({
    //   get() {},
    //   set(val) {}
    // });

    interface User {
      phone: string;
      password: string;
    }

    const user = reactive<User>({
      phone: "13088888888",
      password: "111111",
    });

    const setPassword = () => {
      user.password = "22222";
    };

    // 暴露出去，模板页面才能使用
    return {
      count,
      handleClick,
      user,
      setPassword,
      text,
    };
  },
  components: {
    Child,
  },
});
</script>

<style></style>
